package com.vi.xml.config;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;

public class XmlConfigUtil {

	public static void registerClasses() throws Exception {
		List<Class> classes = getClasses("com.mindtree.vi.xml");
		XStream xstream = new XStream(new Sun14ReflectionProvider());
		for (Class clazz : classes) {
			XStreamAlias alias = ((XStreamAlias) clazz
					.getAnnotation(XStreamAlias.class));
			if (alias != null) {
				System.out.println(alias.value());
				xstream.alias(alias.value(), clazz);
			} else {
				System.out
						.println(clazz.getSimpleName().replace(
								clazz.getSimpleName().charAt(0),
								Character.toLowerCase(clazz.getSimpleName()
										.charAt(0))));
				xstream.alias(
						clazz.getSimpleName().replace(
								clazz.getSimpleName().charAt(0),
								Character.toLowerCase(clazz.getSimpleName()
										.charAt(0))), clazz);
			}
		}
	}

	public static List<Class> getClasses(String packageName) throws Exception {
		String packagePath = packageName.replace('.', '/');
		URL[] classpath = ((URLClassLoader) ClassLoader.getSystemClassLoader())
				.getURLs();
		List<Class> result = new ArrayList<Class>();
		for (URL url : classpath) {
			File file = new File(url.toURI());
			if (file.getPath().endsWith(".jar")) {
				JarFile jarFile = new JarFile(file);
				for (Enumeration<JarEntry> entries = jarFile.entries(); entries
						.hasMoreElements();) {
					String entryName = (entries.nextElement()).getName();
					if (entryName.matches(packagePath + "/\\w*\\.class")) { // get
						// only
						// class
						// files
						// in
						// package
						// dir
						ClassLoader classLoader = new URLClassLoader(
								new URL[] { url });
						String className = entryName.replace('/', '.')
								.substring(0, entryName.lastIndexOf('.'));
						Class clazz = classLoader.loadClass(className);
						result.add(clazz);
					}
				}
			} else { // directory
				File packageDirectory = new File(file.getPath() + "/"
						+ packagePath);
				for (File f : packageDirectory.listFiles()) {
					if (f.getPath().endsWith(".class")) {
						String className = packageName
								+ "."
								+ f.getName().substring(0,
										f.getName().lastIndexOf('.'));
						ClassLoader classLoader = new URLClassLoader(
								new URL[] { url });
						Class clazz = classLoader.loadClass(className);
						result.add(clazz);
					}
				}
			}
		}
		return result;
	}

	// test
	public static void main(String[] args) throws Exception {
		XmlConfigUtil.registerClasses();
	}
}
